package com.lock.method;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.method
 * @ClassName:Test04
 * @Description: boolean hasWaiters(Condition condition) 查询是否有线程正在等待指定的Condition条件
 * @Author: zhangxiaoyu
 * @date 2021/3/8 13:26
 */
public class Test04 {

    static ReentrantLock lock = new ReentrantLock(); //创建锁对象
    static Condition condition = lock.newCondition(); //返回锁定的条件

    static  void  sm(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"lock----------");
            System.out.println("是否有线程正在等待当前condition条件？"+lock.hasWaiters(condition)+"---waitqueuelenth"+
                    lock.getWaitQueueLength(condition)+
                    condition.await(new Random().nextInt(1000), TimeUnit.MICROSECONDS));
                //超时会自动唤醒
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"等待----");
            lock.unlock();
        }

    }


    public static void main(String[] args){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                sm();
            }
        };
        //开启10个线程
        for (int i=0;i<10;i++){
            new Thread(runnable).start();
        }
    }


}
